﻿using FlowCanvas;
using FlowCanvas.Nodes;
using LogSystem;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
using Yoozoo.Gameplay.Liberty;
using Yoozoo.Gameplay.Liberty.AI;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class CreatePropItem : PureFunctionNodeBase
    {
        PropItem _propItem;
        
        [HideInInspector]
        public FlowOutput onPlay;
        public void Invoke(int itemId, Vector3 position, bool groundCheck)
        {
            PropItem propItem = PropItem.CreatePropItem(itemId);
            bool hit = false;
            if (groundCheck)
            {
                RaycastHit raycastHit;
                hit = PhysicsUtils.RaycastNonAlloc(out raycastHit, position+Vector3.up*2, Vector3.down, 10, "cityground");
                if (hit)
                {
                    propItem.transform.position = raycastHit.point;
                }   
            }
    
            _propItem = propItem;
            if (!hit)
            {
                propItem.transform.position = position;
            }
            onPlay?.Call(new Flow());
        }

        protected override void OnRegisterPorts(FlowNode node)
        {
            var p1 = node.AddValueInput<int>("itemId");
            var p2 = node.AddValueInput<Vector3>("position");
            var p3 = node.AddValueInput<bool>("groundCheck");
            node.AddFlowInput(" ", (Flow f) =>
            {
                Invoke(p1.value, p2.value, p3.value);
            });
        
            node.AddValueOutput<PropItem>("propItem", () =>
            {
                return _propItem;
            });
            onPlay = node.AddFlowOutput("Out");
        }
    }
}